<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="退款id" prop="id">
        <el-input
            v-model="queryParams.id"
            placeholder="请输入退款id"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="子订单id" prop="orderDetailId">
        <el-input
            v-model="queryParams.orderDetailId"
            placeholder="请输入子订单id"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="总订单id" prop="orderId">
        <el-input
            v-model="queryParams.orderId"
            placeholder="请输入总订单id"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item label="申请时间" style="width: 308px">
        <el-date-picker
            v-model="daterangeCreateTime"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>

      </el-form-item>
    </el-form>
    <el-radio-group v-model="selectedStatus" size="medium" @change="handleStatusChange">
      <el-radio-button :label="''" style="color: #409EFF;" @click="filterStatus('')">全部</el-radio-button>
      <el-radio-button :label="'1'" style="color: #409EFF;" @click="filterStatus('1')">待审批</el-radio-button>
      <el-radio-button :label="'5'" style="color: #67C23A;" @click="filterStatus('5')">退款成功</el-radio-button>
      <el-radio-button :label="'6'" style="color: #E6A23C;" @click="filterStatus('6')">退款失败</el-radio-button>
      <el-radio-button :label="'2'" style="color: #909399;" @click="filterStatus('2')">取消退款</el-radio-button>
    </el-radio-group>



    <el-table v-loading="loading" :data="refundApplyList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="40" align="center" />
      <el-table-column label="退款id" align="center" prop="id" width="180"/>
      <el-table-column label="子订单id" align="center" prop="orderDetailId" width="180"/>
      <el-table-column label="退款金额" align="center" prop="refundAmount" sortable/>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="refund" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="申请时间" align="center" prop="createTime" width="180" sortable>
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="处理时间" align="center" prop="approveTime" width="180" sortable>
        <template #default="scope">
          <span>{{ parseTime(scope.row.approveTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="退款时间" align="center" prop="finishTime" width="180" sortable>
        <template #default="scope">
          <span>{{ parseTime(scope.row.finishTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="申请人" align="center" prop="createBy" />
      <el-table-column label="处理人" align="center" prop="updateBy" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="300px" fixed="right">
        <template #default="scope">
          <el-button
              v-if="scope.row.status === 1"
              link
              type="primary"
              icon="Check"
              @click="handleUpdateStatus(scope.row, 5)"
              v-hasPermi="['order:refundApply:approve']">
            同意
          </el-button>
          <el-button
              v-if="scope.row.status === 1"
              link
              type="primary"
              icon="Close"
              @click="handleUpdateStatus(scope.row, 6)"
              v-hasPermi="['order:refundApply:reject']">
            拒绝
          </el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['order:refundApply:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['order:refundApply:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改退款申请对话框 -->
    <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
      <el-form ref="refundApplyRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="子订单id" prop="orderDetailId">
          <el-input v-model="form.orderDetailId" placeholder="请输入子订单id" />
        </el-form-item>
        <el-form-item label="总订单id" prop="orderId">
          <el-input v-model="form.orderId" placeholder="请输入总订单id" />
        </el-form-item>
        <el-form-item label="流水支付单号" prop="payOrderNo">
          <el-input v-model="form.payOrderNo" placeholder="请输入流水支付单号" />
        </el-form-item>
        <el-form-item label="流水退款单号" prop="refundOrderNo">
          <el-input v-model="form.refundOrderNo" placeholder="请输入流水退款单号" />
        </el-form-item>
        <el-form-item label="订单所属用户id" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入订单所属用户id" />
        </el-form-item>
        <el-form-item label="退款金额" prop="refundAmount">
          <el-input v-model="form.refundAmount" placeholder="请输入退款金额" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
                v-for="dict in refund"
                :key="dict.value"
                :label="parseInt(dict.value)"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="申请退款原因" prop="refundReason">
          <el-input v-model="form.refundReason" placeholder="请输入申请退款原因" />
        </el-form-item>
        <el-form-item label="退款状态描述" prop="message">
          <el-input v-model="form.message" placeholder="请输入退款状态描述" />
        </el-form-item>
        <el-form-item label="审批人id" prop="approver">
          <el-input v-model="form.approver" placeholder="请输入审批人id" />
        </el-form-item>
        <el-form-item label="审批意见" prop="approveOpinion">
          <el-input v-model="form.approveOpinion" placeholder="请输入审批意见" />
        </el-form-item>
        <el-form-item label="审批备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入审批备注" />
        </el-form-item>
        <el-form-item label="退款失败原因" prop="failedReason">
          <el-input v-model="form.failedReason" placeholder="请输入退款失败原因" />
        </el-form-item>
        <el-form-item label="退款问题说明" prop="questionDesc">
          <el-input v-model="form.questionDesc" placeholder="请输入退款问题说明" />
        </el-form-item>
        <el-form-item label="退款渠道" prop="refundChannel">
          <el-input v-model="form.refundChannel" placeholder="请输入退款渠道" />
        </el-form-item>
        <el-form-item label="处理时间" prop="approveTime">
          <el-date-picker clearable
                          v-model="form.approveTime"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择处理时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="退款时间" prop="finishTime">
          <el-date-picker clearable
                          v-model="form.finishTime"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择退款时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="机构id" prop="insId">
          <el-input v-model="form.insId" placeholder="请输入机构id" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>

        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="RefundApply">
import { listRefundApply, getRefundApply, delRefundApply, addRefundApply, updateRefundApply,updateRefundApplyStatus } from "@/api/order/refundApply";


const { proxy } = getCurrentInstance();
const { refund } = proxy.useDict('refund');
const selectedStatus = ref('');
const refundApplyList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeCreateTime = ref([]);


const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    id: null,
    orderDetailId: null,
    orderId: null,
    status: null,
    createTime: null,

  },
  rules: {
    orderDetailId: [
      { required: true, message: "子订单id不能为空", trigger: "blur" }
    ],
    orderId: [
      { required: true, message: "总订单id不能为空", trigger: "blur" }
    ],
    userId: [
      { required: true, message: "订单所属用户id不能为空", trigger: "blur" }
    ],
    refundAmount: [
      { required: true, message: "退款金额不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "状态不能为空", trigger: "change" }
    ],
    refundReason: [
      { required: true, message: "申请退款原因不能为空", trigger: "blur" }
    ],
    message: [
      { required: true, message: "退款状态描述不能为空", trigger: "blur" }
    ],
    createTime: [
      { required: true, message: "申请时间不能为空", trigger: "blur" }
    ],
    updateTime: [
      { required: true, message: "更新时间不能为空", trigger: "blur" }
    ],
    createBy: [
      { required: true, message: "申请人不能为空", trigger: "blur" }
    ],
    updateBy: [
      { required: true, message: "处理人不能为空", trigger: "blur" }
    ],
    insId: [
      { required: true, message: "机构id不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);
const filterStatus = (status) => {
  queryParams.value.status = status;
  queryParams.value.pageNum = 1;
  getList();
};


/** 查询退款申请列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangeCreateTime && '' != daterangeCreateTime) {
    queryParams.value.params["beginCreateTime"] = daterangeCreateTime.value[0];
    queryParams.value.params["endCreateTime"] = daterangeCreateTime.value[1];
  }
  listRefundApply(queryParams.value).then(response => {
    refundApplyList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}


// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 同意退款申请

function handleUpdateStatus(row, newStatus) {
  // 根据 newStatus 决定使用哪个 URL
  let url;
  if (newStatus === 5) { // 假设5是同意的状态码
    url = `/order/refundApply/approve/${row.id}`;
  } else if (newStatus === 6) { // 假设6是拒绝的状态码
    url = `/order/refundApply/reject/${row.id}`;
  }

  // 调用API更新状态
  updateRefundApplyStatus(url).then(response => {
    if (response.code === 200) {
      // 更新成功，提示用户
      alert("操作成功");
      // 刷新列表
      getList();
    } else {
      // 更新失败，提示用户
      alert("操作失败");
    }
  }).catch(error => {
    // 处理错误
    console.error("操作失败:", error);
  });
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    orderDetailId: null,
    orderId: null,
    payOrderNo: null,
    refundOrderNo: null,
    userId: null,
    refundAmount: null,
    status: null,
    refundReason: null,
    message: null,
    approver: null,
    approveOpinion: null,
    remark: null,
    failedReason: null,
    questionDesc: null,
    refundChannel: null,
    createTime: null,
    approveTime: null,
    finishTime: null,
    updateTime: null,
    createBy: null,
    updateBy: null,
    insId: null
  };
  proxy.resetForm("refundApplyRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeCreateTime.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加退款申请";
}

function handleApprove(row) {
  // 发送请求更新状态为5
  updateRefundApplyStatus(row.id, 5).then(() => {
    // 更新本地状态
    row.status = 5;
    // 可以在这里添加消息提示，例如：
    alert("退款申请已同意");
  }).catch(error => {
    console.error("更新失败:", error);
    // 可以在这里添加错误处理，例如：
    alert("更新失败，请重试");
  });
}

// 更新拒绝状态
function handleReject(row) {
  // 发送请求更新状态为6
  updateRefundApplyStatus(row.id, 6).then(() => {
    // 更新本地状态
    row.status = 6;
    // 可以在这里添加消息提示，例如：
    alert("退款申请已拒绝");
  }).catch(error => {
    console.error("更新失败:", error);
    // 可以在这里添加错误处理，例如：
    alert("更新失败，请重试");
  });
}
/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getRefundApply(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改退款申请";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["refundApplyRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateRefundApply(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addRefundApply(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除退款申请编号为"' + _ids + '"的数据项？').then(function() {
    return delRefundApply(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}


/** 导出按钮操作 */
function handleExport() {
  proxy.download('order/refundApply/export', {
    ...queryParams.value
  }, `refundApply_${new Date().getTime()}.xlsx`)
}

getList();
</script>
